using System.Collections.Generic;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Headspring.Training.Domain;
using Headspring.Training.Domain.Model;
using Headspring.Training.Domain.Services;
using StructureMap;

namespace Headspring.Training.WebUI.Services.Impl
{
	[Pluggable(Keys.DEFAULT)]
	public class HttpUserSession : IUserSession
	{
		private readonly IEmployeeRepository _employeeRepository;

		public HttpUserSession(IEmployeeRepository employeeRepository)
		{
			_employeeRepository = employeeRepository;
		}

		public Employee GetCurrentUser()
		{
			IIdentity identity = HttpContext.Current.User.Identity;
			if(!identity.IsAuthenticated)
			{
				return null;
			}

			Employee currentUser = _employeeRepository.GetByUserName(identity.Name);
			return currentUser;
		}

		public void LogIn(Employee employee)
		{
			FormsAuthentication.RedirectFromLoginPage(employee.UserName, false);
		}

		public void LogOut()
		{
			FormsAuthentication.SignOut();
			FormsAuthentication.RedirectToLoginPage();
		}

		public void PushUserMessage(FlashMessage message)
		{
			ensureFlashMessagesInitialized();
			Stack<FlashMessage> flash = getFlash();
			flash.Push(message);
		}

		public FlashMessage PopUserMessage()
		{
			Stack<FlashMessage> flash = getFlash();
			if(flash.Count == 0)
			{
				return null;
			}

			return flash.Pop();
		}

		private Stack<FlashMessage> getFlash()
		{
			ensureFlashMessagesInitialized();
			HttpSessionState session = HttpContext.Current.Session;
			return (Stack<FlashMessage>)session["flash"];
		}

		private void ensureFlashMessagesInitialized()
		{
			HttpSessionState session = HttpContext.Current.Session;
			Stack<FlashMessage> flash = session["flash"] as Stack<FlashMessage>;
			if(flash == null)
			{
				session["flash"] = new Stack<FlashMessage>();
			}
		}
	}
}